/*UNRES Add this annotation to the document let it is inaccessible*/
const mysql = require('mysql')
var pool;
module.exports = {
  config:{},
  connect(fn, callBack) {
    if (!pool) {
      pool = mysql.createPool(Object.assign({
        connectionLimit:100,//一次创建的最大连接数量
        multipleStatements: true,
        charset:'utf8mb4',
        supportBigNumbers:true,
        bigNumberStrings:true
      }, this.config));
    }
    var _this = this,failTimes = 0;
    pool.getConnection((err,connection) => {
      if (err) {
        console.log('connection connect err', err);
        if(failTimes == 3){
          if(typeof callBack == 'function') callBack({errorMsg:'mysql connection connect err 3 times'})
        }else{
          failTimes ++;
          if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR' || err.code === 'ETIMEDOUT') {
            _this.connect(fn, callBack);
          }
        }
      }else{
        if (typeof fn == 'function') fn(connection);
      }
    })
  },
  eval(s, fn,args) {
    args = args || {};
    new Promise(next => {
      if(args.connection){
        next(args.connection)
      }else{
        this.connect(next,fn)
      }
    }).then(connection => {
      connection.query(s, (err, res) => {
        //db.end();
        //if(!args.connection) connection.release();
        if(!args.connection) {
          pool.releaseConnection(connection);
        }
        if (err) {
          var errorMsg = err.sqlMessage || err.code || '数据库未知错误';
          if (typeof fn == 'function') fn({
            errorMsg: errorMsg
          });
          console.log(`error sql:
          ${s}
          -------------------- 
          ${errorMsg}
          `);
        } else {
          if(args.logs) console.log(s);
          if (typeof fn == 'function') fn(res);
        }
      })
    })
  },
  ///2版本 支持Promise
  evalSync(s, args){
    return new Promise(next => {
      this.eval(s, next,args)
    })
  }
}